<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form ref="loginForm" @submit="login">
      <van-field
        :rules="formRules.mobile"
        v-model="user.mobile"
        placeholder="请输入手机号码"
        name="mobile"
        ><template slot="left-icon"
          ><i class="toutiao toutiao-shouji"></i
        ></template>
      </van-field>
      <van-field
        :rules="formRules.code"
        v-model="user.code"
        placeholder="请输入验证码"
      >
        <template slot="left-icon"
          ><i class="toutiao toutiao-yanzhengma"></i> </template
        ><template #button>
          <van-count-down
            @finish="sending = false"
            v-if="sending"
            :time="time"
            format=" ss 秒"
          />
          <van-button v-else round size="small" @click="sendCode"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block type="info" native-type="submit" :loading="loading"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSms, login } from "@/api/user.js";
export default {
  data() {
    return {
      formRules: {
        mobile: [
          {
            required: true,
            message: "手机号码不能为空",
          },
          {
            pattern: /^1\d{10}$/,
            message: "手机号码不正确",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
          },
          {
            pattern: /^\d{4,6}$/,
            message: "验证码不正确",
          },
        ],
      },
      user: {
        mobile: "",
        code: "",
      },
      time: 60000,
      sending: false,
      loading: false,
    };
  },
  methods: {
    async sendCode() {
      await this.$refs.loginForm.validate("mobile");
      // console.log("验证通过");
      try {
        await sendSms(this.user.mobile);
        this.$toast.success("发送验证码成功");
        this.sending = true;
      } catch (error) {
        console.log(error);
        if (error.response) {
          return this.$toast.fail(error.response.data.message);
        } else {
          return this.$toast.fail("网络异常");
        }
      }
    },
    async login() {
      // console.log("表单提交成功");
      try {
        this.loading = true;
        const res = await login(this.user);
        this.$toast.success("登录成功，即将跳转页面");
        // localStorage.setItem("token", res.data.token);
        this.$store.commit("setUser", res.data);
        // console.log(res);
        // console.log(res.data.data.token);
        this.$router.push("/my");
      } finally {
        this.loading = false;
      }
    },
    // finishFn() {
    //   this.sending = false;
    // },
  },
};
</script>

<style scoped>
.login-btn {
  margin: 16px;
}
</style>